#!/bin/bash

# MIT License
# 
# Copyright (c) 2017 Dan Persons <dpersonsdev@gmail.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# 


# Set defaults:
RUNPARSER="True"
RUNSENTRY="True"
LOGESPBASE="/opt/LogESP"
ENVBASE="/opt/LogESP/env"

usage() {
    echo "Usage: ${0##*/} [{start|stop|restart|clean}] [-hv] [-lps] [-b LOGESPBASE] [-e ENVBASE]"
    echo
    echo "Optional arguments:"
    echo "  -h                      Print this help message"
    echo "  -v                      Print the version number"
    echo "  -l                      Use local EOL date when cleaning"
    echo "  -p                      Run parser only (no sentry)"
    echo "  -s                      Run sentry only (no parser)"
    echo "  -b <LogESP-base>        Set the LogESP base directory"
    echo "  -e <env-base>           Set a virtual environment"
}

case "${1}" in
    start)
        STARTING=1
        shift
        ;;
    stop)
        STOPPING=1
        shift
        ;;
    restart)
        RESTARTING=1
        shift
        ;;
    status)
        STATUSCHECK=1
        shift
        ;;
    clean)
        CLEANING=1
        shift
        ;;
esac

while getopts ":hvlpsb:e:" o; do
    case "${o}" in
        h)
            usage
            exit 0
            ;;
        v)
            VERSIONCHECK=1
            ;;
        l)
            CLEANLOCAL=1
            ;;
        p)
            RUNSENTRY="False"
            ;;
        s)
            RUNPARSER="False"
            ;;
        b)
            LOGESPBASE=${OPTARG}
            ;;
        e)
            ENVBASE=${OPTARG}
            ;;
        *)
            usage
            exit 0
            ;;
    esac
done
shift $((OPTIND-1))

PIDFILE="${LOGESPBASE}/run/logesp.pid"

if ! [ `whoami` = 'root' ]; then
    echo "Root privileges required."
    exit 1
fi

if [ -d "${ENVBASE}" ]; then
    if [ -f "${ENVBASE}/bin/activate" ]; then
        source "${ENVBASE}/bin/activate"
    else
        echo "LogESP virtual env at ${ENVBASE}/bin/activate not found"
    fi
else
    echo "LogESP virtual env base directory ${ENVBASE} not found."
    exit 1
fi

if [ -d "${LOGESPBASE}" ]; then
    cd "${LOGESPBASE}"
else
    echo "LogESP base directory ${LOGESPBASE} not found."
    exit 1
fi

if [ $STARTING ]; then
    if [ -s "${PIDFILE}" ]; then
        echo "PID file ${PIDFILE} already exists. Stop LogESP daemon first."
    else
        read LOGESPPROC WASTE <<< `ps aux | grep 'daemons.logespcore.main' | grep -v grep | awk '{print $2}'`
        if [ ${LOGESPPROC} ]; then
            echo "LogESP already running at PID ${LOGESPPROC}. Stop first."
        else
            export ENVBASE LOGESPBASE RUNPARSER RUNSENTRY PIDFILE
            su -s '/bin/bash' -c 'source "${ENVBASE}/bin/activate" ; python "${LOGESPBASE}/manage.py" shell -c "import daemons.logespcore ; daemons.logespcore.main(parser=${RUNPARSER}, sentry=${RUNSENTRY})" & echo -n "$! " >> "${PIDFILE}"' logespd
        fi
    fi

elif [ $RESTARTING ]; then
    if [ -s "${PIDFILE}" ]; then
        PIDLIST=`cat "${PIDFILE}"`
        for PID in ${PIDLIST[@]}; do
            kill ${PID}
        done
        > "${PIDFILE}"
        #rm -f "${PIDFILE}"
    else
        read LOGESPPROC WASTE <<< `ps aux | grep 'daemons.logespcore.main' | grep -v grep | awk '{print $2}'`
        if [ ${LOGESPPROC} ]; then
            kill "${LOGESPPROC}"
        else
            echo "LogESP daemon not running"
            exit 1
        fi
    fi
    sleep 0.5
    export ENVBASE LOGESPBASE RUNPARSER RUNSENTRY PIDFILE
    su -s '/bin/bash' -c 'source "${ENVBASE}/bin/activate" ; python "${LOGESPBASE}/manage.py" shell -c "import daemons.logespcore ; daemons.logespcore.main(parser=${RUNPARSER}, sentry=${RUNSENTRY})" & echo -n "$! " >> "${PIDFILE}"' logespd

elif [ $STOPPING ]; then
    if [ -s "${PIDFILE}" ]; then
        PIDLIST=`cat "${PIDFILE}"`
        for PID in ${PIDLIST[@]}; do
            kill ${PID}
        done
        > "${PIDFILE}"
        #rm -f "${PIDFILE}"
    else
        read LOGESPPROC WASTE <<< `ps aux | grep 'daemons.logespcore.main' | grep -v grep | awk '{print $2}'`
        if [ ${LOGESPPROC} ]; then
            kill "${LOGESPPROC}"
        else
            echo "LogESP daemon not running."
        fi
    fi

elif [ $CLEANING ]; then
    if [ $CLEANINGLOCAL ]; then
        export ENVBASE LOGESPBASE
        su -s '/bin/bash' -c 'source "${ENVBASE}/bin/activate" ; python "${LOGESPBASE}/manage.py" shell -c "import daemons.cleaner.clean ; daemons.cleaner.clean.clean(local=True)"' logespd
    else
        export ENVBASE LOGESPBASE
        su -s '/bin/bash' -c 'source "${ENVBASE}/bin/activate" ; python "${LOGESPBASE}/manage.py" shell -c "import daemons.cleaner.clean ; daemons.cleaner.clean.clean()"' logespd
    fi

elif [ $STATUSCHECK ]; then
    echo "=== LogESP daemon ==="
    if [ -s ${PIDFILE} ]; then
        PIDLIST=`cat "${PIDFILE}"`
        for PID in ${PIDLIST[@]}; do
            echo "PID on file: $(cat "${PIDFILE}")"
        done
    else
        echo "No PID on file."
    fi
    read LOGESPPROC WASTE <<< `ps aux | grep 'daemons.logespcore.main' | grep -v grep | awk '{print $2}'`
    if [ ${LOGESPPROC} ]; then
        echo "Running PID: ${LOGESPPROC}"
    else
        echo "No PID running."
    fi

elif [ $VERSIONCHECK ]; then
    export ENVBASE LOGESPBASE
    VERSION=`su -s '/bin/bash' -c 'source "${ENVBASE}/bin/activate" ; python "${LOGESPBASE}/manage.py" shell -c "import LogESP; print(LogESP.__version__)"' logespd`
    echo "${0##*/}-$VERSION"
    exit 0	

fi
